package com.shenxuchen.crm.web.interceptor;

import com.shenxuchen.crm.constant.Constants;
import com.shenxuchen.crm.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User loginUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
        if (loginUser == null) {
            // ajax请求，响应json，交给前端来跳转
            Boolean isAjax = request.getHeader("X-Requested-With") != null;
            if (isAjax) {
                Map result = new HashMap();
                result.put("success", false);
                result.put("errMsg", "登录超时！请重新登录！");
                // 前端判断跳转到登录页面的依据
                result.put("reLogin", true);

                String json = Constants.JACKSON.writeValueAsString(result);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);
            }
            // 传统请求，强制跳转到登录页面
            else {
                response.sendRedirect("/");
            }
            return false;
        }
        return true;
    }
}
